<?php

namespace App\Http\Controllers;

use App\Services\Wechat\WechatPaymentService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class PaymentController extends Controller
{
    protected $wechatPaymentService;

    public function __construct(WechatPaymentService $wechatPaymentService)
    {
        $this->wechatPaymentService = $wechatPaymentService;
    }

    // 处理支付回调
    public function notify(Request $request)
    {
        try {
            // 使用新的服务处理回调 - 修复参数传递
            $decryptedData = $this->wechatPaymentService->handleNotify($request);

            // 处理订单逻辑
            $outTradeNo = $decryptedData['out_trade_no'];
            $transactionId = $decryptedData['transaction_id'];
            $totalAmount = $decryptedData['amount']['total'];

            // 更新订单状态等操作...
            Log::info('支付回调处理成功', [
                'out_trade_no' => $outTradeNo,
                'transaction_id' => $transactionId,
                'amount' => $totalAmount
            ]);

            // 返回成功响应
            return response()->json([
                'code' => 'SUCCESS',
                'message' => '成功'
            ]);
        } catch (\Exception $e) {
            Log::error('微信支付回调处理失败: ' . $e->getMessage());

            // 返回失败响应
            return response()->json([
                'code' => 'FAIL',
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * JSAPI支付接口
     */
    public function jsapiPay(Request $request)
    {
        try {
            $openid = $request->input('openid');
            $orderNo = $request->input('order_no');
            $amount = $request->input('amount');
            $description = $request->input('description', '商品支付');
            
            // 使用WeChatPayService处理JSAPI支付
            $wechatPayService = new \App\Services\WeChatPayService();
            $result = $wechatPayService->jsapiPay($openid, $orderNo, $amount, $description);
            
            return response()->json([
                'code' => 'SUCCESS',
                'data' => $result
            ]);
        } catch (\Exception $e) {
            Log::error('JSAPI支付失败: ' . $e->getMessage());
            
            return response()->json([
                'code' => 'FAIL',
                'message' => $e->getMessage()
            ]);
        }
    }
}